package com.jingdong.service.impl;


import com.jingdong.pojo.GuanZhuDetail;
import com.jingdong.pojo.QianDaoDetail;
import com.jingdong.repository.GuanZhuRepository;
import com.jingdong.repository.QianDaoRepository;
import com.jingdong.service.QianDaoDetailCategoryService;
import com.jingdong.utils.ResultVOUtil;
import com.jingdong.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.invoke.MethodHandles;

@Service
@Transactional
@CacheConfig
public class QianDaoDetailCategoryServiceImpl  implements QianDaoDetailCategoryService {
    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Autowired
    private QianDaoRepository qianDaoRepository;

    @Override
    @Cacheable(value = "qiandao", key = "#a1")
    public Page<QianDaoDetail> findAll(Integer page, Integer size) throws Exception {
        try {
            Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "id");
            return qianDaoRepository.findAll(pageable);
        }catch (Exception e){
            logger.error(e.getLocalizedMessage());
            return null;
        }
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames="qiandao",allEntries = true)
    public ResultVO save(QianDaoDetail qianDaoDetail) throws Exception {
        if (qianDaoDetail != null) {
            try {
                QianDaoDetail isExit = qianDaoRepository.findQiandaoDeatil(qianDaoDetail.getUrl());
                if (isExit==null){
                    synchronized (this){
                        QianDaoDetail save = qianDaoRepository.save(qianDaoDetail);
                        if (save==null){
                            return ResultVOUtil.error(-1,"数据插入错误！");
                        }else{
                            return ResultVOUtil.succecss(save);
                        }
                    }
                }else {
                    return ResultVOUtil.error(-1,"数据重复，请重新插入！");
                }
            } catch (Exception e){
                logger.error(e.getLocalizedMessage());
                return ResultVOUtil.error(-1,"未知错误！");
            }
        }else {
            return ResultVOUtil.error(-1,"请重新输入数据！");
        }
    }
}
